﻿/* 
* Copyright (c) 2009, SCUT 06级计科2班软件工程第6小组
* All rights reserved. 
*
* 作    者：莫树聪
* 完成日期：2009年7月*日 
*  
* 摘    要：处理用户管理业务逻辑
*
* 备    注：
*
*/
using System;
using System.Security.Cryptography;
using System.IO;

/**DES加解算法
 * 如是明文长度是N. 
 * N是8的倍数,加密出来的密文长度是   N+8 
 * N不是8的倍数,加密出来的密文长度是   (N/8+1)*8 
 */
public static class DESCoder
{
	//将一个字符串转换为一个8字节的DES密钥，过程可重复
	static public Byte[] ExtractKey(String str)
	{
		Byte[] hashKey = Utility.Hash.Md5(str);
		Byte[] key=new Byte[8];		
		for(Int32 i=0;i<8;++i)
			key[i]=hashKey[i];
		return key;
	}
	//返回一个随机8字节的DES密钥
	static public Byte[] GetRandKey()
	{
		Byte[] key = new Byte[8];
		Random r = new Random(DateTime.Now.Millisecond);
		r.NextBytes(key);
		return key;
	}
	//DES加密，密钥64bit，8字节
	public static Byte[] Encrypt(Byte[] key, Byte[] plainText)
	{
		DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
		return Transform(
			dCSP.CreateEncryptor(key, INIT_VECTOR), plainText);
	}
	//DES解密，密钥64bit，8字节
	public static Byte[] Decrypt(Byte[] key, Byte[] cypherText)
	{
		DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
		return Transform(
			dCSP.CreateDecryptor(key, INIT_VECTOR), cypherText);
	}
	private static Byte[] Transform(ICryptoTransform transor, Byte[] plainText)
	{
		try
		{
			MemoryStream ms = new MemoryStream();
			CryptoStream cs = new CryptoStream(ms, transor, CryptoStreamMode.Write);
			cs.Write(plainText, 0, plainText.Length);
			cs.FlushFinalBlock();
			return ms.ToArray();
		}
		catch (Exception)
		{
			return null;
		}
	}
	//初始化向量
	private static Byte[] INIT_VECTOR ={ 
		0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
}
